package leetcode.D100.T47;

import java.util.*;

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> results = new LinkedList<>();
        boolean[] used = new boolean[nums.length];
        List<Integer> path = new LinkedList<>();
        Arrays.sort(nums);
        dfs(nums, used, path, results);
        return results;
    }
    private void dfs(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> results) {
        if(path.size() == nums.length) {
            results.add(new ArrayList<>(path));
            return;
        }
        int last = 100;
        for (int i = 0; i < nums.length; i++) {
            if(used[i] || (i > 0 && last == nums[i])) {
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            dfs(nums, used, path, results);
            used[i] = false;
            path.remove(path.size()-1);
            last = nums[i];
        }
    }
}
